clear all;

cd ..; cd ..; cd ..; cd ..; 
load('code_main_model\6_implied_w_r\computation_results\data.mat');
cd 'code_figure_table\maintext\Table 2\model';

r_end_index=min(find(r_guess(:,1)==0))-1;
r=r_guess(r_end_index,:);
rev_backward(1:period_trans-1,1:nmkt,1:nz,1:nb,1:ntheta)=0;


for i_t=1:period_trans-1
    for i_mkt=1:nmkt
        for i_z=1:nz
            for i_b=1:nb
                for i_theta=1:ntheta
                    k=lin_interpo2(nb, ntheta, gridb, gridtheta, squeeze(gk_backward(i_t,i_mkt, i_z,:,:)), gridb(i_b), gridtheta(i_theta));
                    labor=lin_interpo2(nb, ntheta, gridb, gridtheta, squeeze(gl_backward(i_t,i_mkt, i_z,:,:)), gridb(i_b), gridtheta(i_theta));
                    if ((k<1e-10) || (labor<1e-10))
                        k=0;
                        labor=0;
                    end
                    y=Z(i_mkt)*gridz(i_z)*(k^alpha*labor^(1-alpha))^(1-nu);

                    b=gridb(i_b);
                    theta=gridtheta(i_theta);
                    m=b*theta;
                    a=b*(1-theta);

                    if (adjust_backward(i_t,i_mkt,i_z,i_b,i_theta)==1)
                        rev_backward(i_t,i_mkt,i_z,i_b,i_theta)=a*r(i_t);

                    elseif (adjust_backward(i_t,i_mkt,i_z,i_b,i_theta)==2)
                        rev_backward(i_t,i_mkt,i_z,i_b,i_theta)=a*r(i_t);

                    elseif (adjust_backward(i_t,i_mkt,i_z,i_b,i_theta)==3)
                        rev_backward(i_t,i_mkt,i_z,i_b,i_theta)=y+a*r(i_t);
                        
                    elseif (adjust_backward(i_t,i_mkt,i_z,i_b,i_theta)==4)
                        rev_backward(i_t,i_mkt,i_z,i_b,i_theta)=y+a*r(i_t);
                        
                    elseif (adjust_backward(i_t,i_mkt,i_z,i_b,i_theta)==5)
                        rev_backward(i_t,i_mkt,i_z,i_b,i_theta)=y+a*r(i_t);
                        
                    elseif (adjust_backward(i_t,i_mkt,i_z,i_b,i_theta)==6)
                        rev_backward(i_t,i_mkt,i_z,i_b,i_theta)=y+a*r(i_t);
                    end
                    
                end
            end
        end
    end
end

save('rev_backward.mat','rev_backward');